import React, { Component } from 'react';
import { Upload, Icon, message, Button } from 'antd';
import s from './index.less';
import { post } from '@u/ajax';

const valToList = (value) => {
  let fileList = [];
  if (value) {
    if (value instanceof Array) {
      fileList = value;
    } else if (typeof value === 'string'){
      fileList = [{
        fileUrl: value,
        fileType: 10
      }]
    }else {
      fileList = [value];
    }
  }
  return fileList;
};

// 图片查看和上传
class Comp extends Component {
  constructor(p) {
    const { number = 1, onlySee } = p;
    super(p);
    //value:文件列表
    //onlySee:是否只是查看
    //number:规定可上传文件的数量，0代表无限制
    let fileNum = number === 0 ? 9999 : number;
    this.state = {
      loading: false,
      onlySee,
      fileNum,
    };
  }

  beforeUpload = (file) => {
    const arr = ['text/javascript'];
    if (arr.indexOf(file.type) >= 0) {
      message.error('不要上传脚本文件');
      return false;
    }
  };
  onUpload = async ({ file }) => {
    const { onChange, onlyOne, button, value } = this.props;
    this.setState({ loading: true });
    let fd = new FormData();
    fd.append('formbody', file);
    fd.append('type', 'file');
    const res = await post('/file/upload', fd);
    if (res.success) {
      let data = res.data[0];
      let val = [
        ...valToList(value),
        data,
      ];
      let newVal=null
      if (button){
        newVal=val[0].fileUrl
      }else if (onlyOne) {
        newVal=val[0]
      }else {
        newVal=val
      }
      // console.log(newVal)
      onChange && onChange(newVal)
    } else {
      // 上传失败
    }
    this.setState({ loading: false });
  };
  onSee = ({ fileUrl }) => {
    window.open(fileUrl);
  };
  onDelete = async (file, index) => {
    const { onChange, value } = this.props;
    let fileList = valToList(value);
    fileList.splice(index, 1);
    onChange && onChange(fileList.length ? fileList : null);
  };
  renderLoading = () => {
    return (
      <div><Icon type={'loading'} style={{ fontSize: 28 }}/></div>
    );
  };

  render() {
    const { number, button, value } = this.props;
    const { loading, fileNum, onlySee } = this.state;
    let fileList = valToList(value);
    // console.log(fileList)
    return (
      <div className={s['box']}>
        {onlySee || fileList.length >= fileNum ?
          null :
          <Upload
            multiple={number === 0}
            disabled={loading}
            beforeUpload={this.beforeUpload}
            customRequest={this.onUpload}
            showUploadList={false}
          >
            {button
              ? <Button type={'primary'}>上传</Button>
              : <div className={s['upload-btn-box']}>
                {
                  loading
                    ? this.renderLoading()
                    : <div>上传</div>
                }
              </div>}
          </Upload>}
        {fileList.map((v, i) => {
          return (
            <div key={i} className={s['list-item']}>
              {v.fileType === 10
                ? <div className={s['img-box']} style={{ backgroundImage: `url(${v.fileUrl})` }}/>
                : <div className={s['text-box']}>
                  <Icon type="file-text"/>
                  {v.fileName}
                </div>
              }
              <div className={s['item-btns']}>
                <Icon className={s['btn-icon']} type={'eye'} onClick={() => this.onSee(v)}/>
                {!onlySee && <Icon className={s['btn-icon']} type={'delete'} onClick={() => this.onDelete(v, i)}/>}
              </div>
            </div>
          )
        })}
      </div>
    );
  }
}

export default Comp;
